package com.enation.app.javashop.buyer.api.goods;

import com.alibaba.fastjson.JSON;
import com.ctc.wstx.util.DataUtil;
import com.enation.app.javashop.core.client.goods.GoodsClient;
import com.enation.app.javashop.core.distribution.model.dos.DistributionDO;
import com.enation.app.javashop.core.distribution.model.dos.DistributionGoods;
import com.enation.app.javashop.core.distribution.service.DistributionGoodsManager;
import com.enation.app.javashop.core.distribution.service.DistributionManager;
import com.enation.app.javashop.core.goods.model.dos.CategoryDO;
import com.enation.app.javashop.core.goods.model.dos.GoodsDO;
import com.enation.app.javashop.core.goods.model.dos.GoodsGalleryDO;
import com.enation.app.javashop.core.goods.model.dto.TagsDTO;
import com.enation.app.javashop.core.goods.model.enums.GoodsType;
import com.enation.app.javashop.core.goods.model.vo.CacheGoods;
import com.enation.app.javashop.core.goods.model.vo.GoodsParamsGroupVO;
import com.enation.app.javashop.core.goods.model.vo.GoodsShowDetail;
import com.enation.app.javashop.core.goods.model.vo.GoodsSkuVO;
import com.enation.app.javashop.core.goods.service.*;
import com.enation.app.javashop.core.goodssearch.model.GoodsTagIndex;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanGoodsDO;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanGoodsManager;
import com.enation.app.javashop.core.shop.model.vo.ShopVO;
import com.enation.app.javashop.core.shop.service.ShopManager;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.exception.ResourceNotFoundException;
import com.enation.app.javashop.framework.util.CurrencyUtil;
import com.enation.app.javashop.framework.util.DateUtil;
import com.enation.app.javashop.framework.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品控制器
 *
 * @author fk
 * @version v2.0
 * @since v7.0.0 2018-03-21 11:23:10
 */
@RestController
@RequestMapping("/goods")
@Api(description = "商品相关API")
public class GoodsBuyerController {

	@Autowired
	private GoodsQueryManager goodsQueryManager;
	@Autowired
	private GoodsManager goodsManager;
	@Autowired
	private GoodsParamsManager goodsParamsManager;
	@Autowired
	private CategoryManager categoryManager;
	@Autowired
	private GoodsGalleryManager goodsGalleryManager;
	@Autowired
	private DistributionGoodsManager distributionGoodsManager;
	@Autowired
	private ShetuanGoodsManager shetuanGoodsManager;
	@Autowired
	protected GoodsClient goodsClient;
	@Autowired
	private DistributionManager distributionManager;

	@Autowired
	private TagsManager tagsManager;

	@Autowired
	private ShopManager shopManager;

	@GetMapping("/ip")
	public Map ip() throws UnknownHostException {
		InetAddress addr = InetAddress.getLocalHost();
		String ip=addr.getHostAddress();
		String hostName=addr.getHostName();
		Map map  = new HashMap();
		map.put("ip",ip);
		map.put("hostName",hostName);
		return map;

	}

    @ApiOperation(value = "浏览商品的详情,静态部分使用")
    @ApiImplicitParam(name = "goods_id", value = "分类id，顶级为0", required = true, dataType = "int", paramType = "path")
    @GetMapping("/{goods_id}")
    public GoodsShowDetail getGoodsDetail(@PathVariable("goods_id") Integer goodsId) {

		GoodsDO goods = goodsQueryManager.getModel(goodsId);
		GoodsShowDetail detail = new GoodsShowDetail();
		if (goods == null){
			throw new ResourceNotFoundException("不存在此商品");
		}
		BeanUtils.copyProperties(goods,detail);

		Integer goodsOff = 0;
		//商品不存在，直接返回
		if(goods == null){
			detail.setGoodsOff(goodsOff);
			return detail;
		}
		//分类
		CategoryDO category = categoryManager.getModel(goods.getCategoryId());
		detail.setCategoryName(category == null ? "":category.getName());
		//上架状态
		if(goods.getMarketEnable()==1){
			goodsOff = 1;
		}
		detail.setGoodsOff(goodsOff);
		//参数
		List<GoodsParamsGroupVO> list = this.goodsParamsManager.queryGoodsParams(goods.getCategoryId(),goodsId);
		detail.setParamList(list);
		//相册
		List<GoodsGalleryDO> galleryList = goodsGalleryManager.list(goodsId);
		detail.setGalleryList(galleryList);

		//商品好平率
		detail.setGrade(goodsQueryManager.getGoodsGrade(goodsId));

		// 只有团长计算商品佣金
        DistributionGoods distributionGoods = distributionGoodsManager.getModel(goodsId);
        //商品佣金 计算
        BigDecimal firstCommissionDisplay = BigDecimal.ZERO;
        BigDecimal subsidyDisplay = BigDecimal.ZERO;
        BigDecimal goodsPrice = BigDecimal.ZERO;
        BigDecimal percentage = new BigDecimal(100);
        // 先查询当前商品是否是团购商品(es_shetuan_goods)，不是团购商品再查询普通商品佣金比例(es_distribution_goods)
        Integer[] goodsIds = {goodsId};
        List<ShetuanGoodsDO> shetuanGoodsDOS = shetuanGoodsManager.querySheuanGoodsByGoodsIds(goodsIds);
        if(shetuanGoodsDOS != null && shetuanGoodsDOS.size() > 0 ){
            ShetuanGoodsDO shetuanGoodsDO = shetuanGoodsDOS.get(0);
            // 一级分销比例
            BigDecimal firstRate = new BigDecimal(shetuanGoodsDO.getFirstRate());
            goodsPrice =  new BigDecimal(shetuanGoodsDO.getShetuanPrice());
            firstCommissionDisplay = goodsPrice.multiply(firstRate).divide(percentage,2,BigDecimal.ROUND_HALF_UP);
        }else{
            goodsPrice = new BigDecimal(goods.getPrice());
            if(distributionGoods != null){
                // 一级分销比例
                BigDecimal grade1Rebate = new BigDecimal(distributionGoods.getGrade1Rebate());
                firstCommissionDisplay = goodsPrice.multiply(grade1Rebate).divide(percentage,2,BigDecimal.ROUND_HALF_UP);
            }
        }
        if(distributionGoods != null){
            Double subsidyRate1 = distributionGoods.getSubsidyRate();
            if(subsidyRate1 != null && subsidyRate1 > 0){
                // 平台补贴
                BigDecimal subsidyRate = new BigDecimal(subsidyRate1);
                subsidyDisplay = goodsPrice.multiply(subsidyRate).divide(percentage,2,BigDecimal.ROUND_HALF_UP);
            }

        }
        // 分享(一级)佣金
        detail.setFirstCommissionDisplay(firstCommissionDisplay.doubleValue());
        // 平台补贴
        detail.setSubsidyDisplay(subsidyDisplay.doubleValue());

		//添加商品标签
		Map<Integer, Integer> goodsIdAndSellerId = new HashMap<>();
		goodsIdAndSellerId.put(goodsId, goods.getSellerId());
		Map<Integer, List<TagsDTO>> allGoodsTags = this.tagsManager.getAllGoodsTags(goodsIdAndSellerId);
		if (allGoodsTags != null) {
			List<TagsDTO> tagsDTOList = allGoodsTags.get(goodsId);
			detail.setGoodsDetailsTags(this.tagsManager.tagsFilterAndComp("goodsDetailsTags", tagsDTOList));
		}

		// 如果是虚拟商品，返回过期时间
		if (GoodsType.VIRTUAL.name().equals(goods.getGoodsType())) {
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.DAY_OF_MONTH, goods.getExpiryDay());
			detail.setExpiryDayText(sf.format(calendar.getTime()));

			ShopVO shopVO=shopManager.getShop(detail.getSellerId());
			detail.setShopLat(shopVO.getShopLat());
			detail.setShopLng(shopVO.getShopLng());
			detail.setSellerPhone(shopVO.getLinkPhone());
			detail.setSellerLogo(shopVO.getShopLogo());
			String shopAddress=shopVO.getShopProvince().concat(shopVO.getShopCity()).concat(shopVO.getShopCounty())
					.concat(shopVO.getShopTown()).concat(shopVO.getShopAdd());
			detail.setSellerAddress(shopAddress);
		}




		return detail;
	}

    @ApiOperation(value = "获取sku信息，商品详情页动态部分")
    @ApiImplicitParam(name = "goods_id", value = "商品id", required = true, dataType = "int", paramType = "path")
    @GetMapping("/{goods_id}/skus")
    public List<GoodsSkuVO> getGoodsSkus(@PathVariable("goods_id") Integer goodsId) {

        CacheGoods goods = goodsQueryManager.getFromCache(goodsId);

        return goods.getSkuList();
    }

    @ApiOperation(value = "记录浏览器商品次数", notes = "记录浏览器商品次数")
    @ApiImplicitParam(name = "goods_id", value = "商品ID", required = true, paramType = "path", dataType = "int")
    @GetMapping(value = "/{goods_id}/visit")
    public Integer visitGoods(@PathVariable("goods_id") Integer goodsId) {

        return this.goodsManager.visitedGoodsNum(goodsId);
    }

	@ApiOperation(value = "查看商品是否在配送区域 1 有货  0 无货", notes = "查看商品是否在配送区域")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "goods_id", value = "商品ID", required = true, paramType = "path", dataType = "int"),
			@ApiImplicitParam(name = "area_id", value = "地区ID", required = true, paramType = "path", dataType = "int")
	})
	@GetMapping(value = "/{goods_id}/area/{area_id}")
	public Integer checkGoodsArea(@PathVariable("goods_id") Integer goodsId,@PathVariable("area_id") Integer areaId) {

		return this.goodsQueryManager.checkArea(goodsId,areaId);
	}

}
